package com.niit.controller;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.niit.pojo.Product;
import com.niit.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import static com.niit.utils.ByteArrayToBase64Adapter.GSON;

@RestController
@RequestMapping("/api/product")
public class ProductController {
    @Autowired
    private ProductService productService;

    // 添加产品接口
    @RequestMapping("/add")
    public String addProduct(Product product) {
        JsonObject jsonObject = new JsonObject();
        List<Product> products = productService.queryProduct(new Product(product.getProductName()));
        if(products == null || products.size() == 0){
            int i = productService.addProduct(product);
            jsonObject.addProperty("code", i);
        }else {
            jsonObject.addProperty("code", 0);
        }
        return jsonObject.toString();
    }


    // 根据产品ID删除产品接口
    @RequestMapping("/delete")
    public String deleteProduct(Product product) {
        JsonObject jsonObject = new JsonObject();
        List<Product> products = null;
        if(product.getPid() == null){
            products = productService.queryProduct(new Product(product.getProductName()));
        }
        if(products != null){
            int i = productService.deleteProductById(products.get(0).getPid());
            jsonObject.addProperty("code", i);
        }else {
            jsonObject.addProperty("code", 0);
        }
        return jsonObject.toString();
    }

    // 根据产品ID查询产品详情接口
    @RequestMapping("/detail")
    public Product getProductDetail(int productId) {
        return productService.getProductById(productId);
    }

    // 更新产品接口
    @RequestMapping("/update")
    public String updateProduct(Product product) {
        JsonObject jsonObject = new JsonObject();
        int i = productService.updateProduct(product);
        jsonObject.addProperty("code", i);
        return jsonObject.toString();
    }

//    @RequestMapping("/search")

    // 获取所有产品列表接口
    @RequestMapping("/list")
    public String getProductList(Product product) {
        JsonObject jsonObject = new JsonObject();
        List<Product> products = productService.queryProduct(product);
        if(products != null &&products.size() >0){
            jsonObject.addProperty("code", 1);
            jsonObject.add("success", GSON.toJsonTree(products).getAsJsonArray());
        }else {
            jsonObject.addProperty("code", 0);
        }
        return jsonObject.toString();
    }
}
